package com.eat.fish_service.netty_client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author CZF
 * <p>
 * 用来管理连接通道
 */
@Slf4j
public class ManageConnections {
    //key为鱼缸id，value为鱼缸的连接通道
    public static Map<Long, Channel> channelList = new ConcurrentHashMap<>();

    //把客户端加入到连接管理中，便于通过接口连接鱼缸的服务端
    public static Bootstrap bootstrap;

    //通过channel获取鱼缸id
    public static Long getAquariumId(Channel channel) {

        for (Long key : ManageConnections.channelList.keySet()) {
            if (ManageConnections.channelList.get(key) == channel) {
                return key;
            }
        }
        //表示集合中不存在此id
        return 0L;
    }

    //更新
    public static boolean updateData(Long aquariumId) {
        try {
            Channel channel = channelList.get(aquariumId);
            Message message = new Message();
            message.setHead(new byte[]{4, 4, 4, 4});
            message.setLen(new byte[]{1});
            message.setUpdate(new byte[]{1});

            channel.writeAndFlush(message).sync();
            Thread.sleep(1000); //睡个1秒，等数据库更新
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
